<?php
// 应用公共文件
/**
 * 错误返回
 * @param string $msg
 * @param String $data
 * @param int $code
 * @return \think\response\Json
 */
function error($msg="",$data="",$code=400){
    return json(['code'=>$code,'msg'=>$msg,'data'=>$data]);
}


/**
 * 成功返回
 * @param string $msg
 * @param String $data
 * @param int $code
 * @return \think\response\Json
 */
function success($msg="",$data="",$code=200){
    return json(['code'=>$code,'msg'=>$msg,'data'=>$data]);
}


/**
 * 异常500返回
 * @param string $msg
 * @param string $data
 * @param int $code
 * @return \think\response\Json
 */
function exceptionHandel($msg="",$data="",$code=500){
    return json(['code'=>$code,'msg'=>$msg,'data'=>$data],500);
}


/**
 * 自定义json返回数据
 * @param $param
 * @param $http_code
 */
function json_return($param,$http_code=200){
    static $http = array (
        100 => "HTTP/1.1 100 Continue",
        101 => "HTTP/1.1 101 Switching Protocols",
        200 => "HTTP/1.1 200 OK",
        201 => "HTTP/1.1 201 Created",
        202 => "HTTP/1.1 202 Accepted",
        203 => "HTTP/1.1 203 Non-Authoritative Information",
        204 => "HTTP/1.1 204 No Content",
        205 => "HTTP/1.1 205 Reset Content",
        206 => "HTTP/1.1 206 Partial Content",
        300 => "HTTP/1.1 300 Multiple Choices",
        301 => "HTTP/1.1 301 Moved Permanently",
        302 => "HTTP/1.1 302 Found",
        303 => "HTTP/1.1 303 See Other",
        304 => "HTTP/1.1 304 Not Modified",
        305 => "HTTP/1.1 305 Use Proxy",
        307 => "HTTP/1.1 307 Temporary Redirect",
        400 => "HTTP/1.1 400 Bad Request",
        401 => "HTTP/1.1 401 Unauthorized",
        402 => "HTTP/1.1 402 Payment Required",
        403 => "HTTP/1.1 403 Forbidden",
        404 => "HTTP/1.1 404 Not Found",
        405 => "HTTP/1.1 405 Method Not Allowed",
        406 => "HTTP/1.1 406 Not Acceptable",
        407 => "HTTP/1.1 407 Proxy Authentication Required",
        408 => "HTTP/1.1 408 Request Time-out",
        409 => "HTTP/1.1 409 Conflict",
        410 => "HTTP/1.1 410 Gone",
        411 => "HTTP/1.1 411 Length Required",
        412 => "HTTP/1.1 412 Precondition Failed",
        413 => "HTTP/1.1 413 Request Entity Too Large",
        414 => "HTTP/1.1 414 Request-URI Too Large",
        415 => "HTTP/1.1 415 Unsupported Media Type",
        416 => "HTTP/1.1 416 Requested range not satisfiable",
        417 => "HTTP/1.1 417 Expectation Failed",
        500 => "HTTP/1.1 500 Internal Server Error",
        501 => "HTTP/1.1 501 Not Implemented",
        502 => "HTTP/1.1 502 Bad Gateway",
        503 => "HTTP/1.1 503 Service Unavailable",
        504 => "HTTP/1.1 504 Gateway Time-out"
    );
    header('Content-type:text/json');
    // 设置请求方法
    header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS");
    // 设置跨域允许包含的头
    header("Access-Control-Allow-Headers: Authorization, Source, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With ,Version ,Platform");
    //设置允许所有域访问
    header("Access-Control-Allow-Origin: *");
    header($http[$http_code]);
    echo json_encode($param);
    exit();
}



/**
 * 验证参数
 * @param $param1
 * @param $param2
 */
function validateParam($param1,$param2=''){
    $input=input();
    if(!empty($param1)){
        if(is_string($param1)){
            $param1=explode(',',$param1);
        }
        foreach ($param1 as $v){
            if(!isset($input[$v])){
                json_return(['code'=>0,'msg'=>"参数:{$v}不存在"]);
            }
        }
    }else{
        json_return(['code'=>0,'msg'=>"校验参数错误"]);
    }
    //判断参数是否为空
    if(!empty($param2)){
        if(is_string($param2)){
            $param2=explode(',',$param2);
        }
        foreach ($param2 as $v){
            if($input[$v] === "" || $input[$v] === null){
                json_return(['code'=>0,'msg'=>"参数:{$v}不能为空"]);
            }
        }
    }

    return $input;
}


/**
 * 密码加密方法
 * @param string $password 加密的字符串
 * @param string $authCode 加密的密钥
 * @return string
 */
function sp_password($password,$authCode=''){
    if(empty($authCode)){
        $authCode=config('system.authCode');
    }
    $result="###".md5(md5($authCode.$password));
    return $result;
}


/**
 * 获取菜单的树形菜单
 * @param $all_menu
 * @param int $parentId
 * @return array
 */
function getMenuTree($all_menu,$parentId=0){
    $tree=[];
    //获取所有条线的
    foreach ($all_menu as $v) {
        if ($v['parentId'] == $parentId) {
            $v['children']=getMenuTree($all_menu,$v['id']);
            if($v['alwaysShow'] == 1){
                $v['alwaysShow'] = true;
            }else{
                $v['alwaysShow'] = false;
            }
            if($v['dot'] == 1){
                $v['dot'] = true;
            }else{
                $v['dot'] = false;
            }
            if($v['hidden'] == 1){
                $v['hidden'] = true;
            }else{
                $v['hidden'] = false;
            }
            if($v['hidden'] == 1){
                $v['hidden'] = true;
            }else{
                $v['hidden'] = false;
            }
            $tree[] = $v;
        }
    }
    return $tree;
}


/**
 * 获取分类的树状结构
 * @param $all_category
 * @param int $parentId
 * @return array
 */
function getCategoryTree($all_category,$parentId=0){
    $tree=[];
    //获取所有条线的
    foreach ($all_category as $v) {
        if ($v['pid'] == $parentId) {
            $v['children']=getCategoryTree($all_category,$v['id']);
            $tree[] = $v;
        }
    }
    return $tree;
}


/**
 * 获取当前时间
 * @param string $type
 * @return false|int|string
 */
function currentTime($type='common'){
    if($type == 'common'){
        return date('Y-m-d H:i:s');
    }else{
        return time();
    }
}

/**
 * 计算分页的起始位置
 * @param $pageNo
 * @param $pageSize
 * @return float|int
 */
function makeOffset($pageNo,$pageSize){
    return ($pageNo-1)*$pageSize;
}


/**
 * 生成编号
 * @param $letter
 * @param $max_id
 * @return string
 */
function makeNo($letter,$max_id){
    $str=$letter.str_pad(($max_id+1),6,'0',STR_PAD_LEFT );
    return $str;
}


/**
 * 创建唯一编号的数字编号
 * @param string $char
 * @return string
 */
function createNo($char='') {
    $order_id_main = date('YmdHis') . rand(10000, 99999);
    $order_id_len = strlen($order_id_main);
    $order_id_sum = 0;
    for ($i = 0; $i < $order_id_len; $i++) {
        $order_id_sum += (int)(substr($order_id_main, $i, 1)); //这里对生成的随机序列进行加法运算使重复率降低
    };
    $nid = $char.$order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
    return $nid;
}

/**
 * 获取用户的id
 * @return mixed
 */
function uid(){
    return UID;
}


/**
 * 判断是否登录或者返回用户的id
 * @return bool|mixed
 */
function isLogin(){
    $token=request()->header('Authorization');
    if(empty($token)){
        $token = request()->request('token');
    }
    if(empty($token)){
        return false;
    }
    //判断token是否为非法的token
    $key = config('system.tokenKey');
    try {
        $token_arr = (array)\Firebase\JWT\JWT::decode($token, $key, array('HS256'));
        //判断token是否过期
        if (isset($token_arr['user_id']) && isset($token_arr['expire_time'])) {
            if (!empty($token_arr['user_id']) && !empty($token_arr['expire_time'])) {
                //判断时间是否过期
                if(time() <= $token_arr['expire_time']) {
                    return $token_arr['user_id'];
                }else{
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    } catch (\UnexpectedValueException $exception) {
        return false;
    }
}


/**
 * @param $time
 * @param $day
 * @return false|string
 */
function makeDay($time,$day){
    if(!is_int($time)){
        $time = strtotime($time);
    }
    return date('Y-m-d H:i:s',strtotime($day,$time));
}


/**
 * 发送创蓝短信
 * @param $msg
 * @param array $phone
 * @param string $uid
 * @param bool $report
 * @return mixed
 */
function sendDx($msg,$phone=[],$uid='',$report=false){
    $param['account']='';
    $param['password']='';
    $param['msg']="".$msg;//长度不能超过536个字符，签名需要加在内容里
    $param['phone']=implode(',',$phone);//多个手机号码使用英文逗号分隔
    $param['report']=$report;
    $param['uid']=$uid;
    $url='http://smssh1.253.com/msg/v1/send/json';
    $response=http_post_json($url,json_encode($param));
    return $response;
}


/**
 * 发起post请求
 * @param $url
 * @param $param
 * @param string $token
 * @return mixed
 */
function http_post_json($url, $param,$token='')
{
    if(!empty($token)) {
        $jsonStr = json_encode($param);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr),
                'access-token: ' . $token
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $response;
    }else{
        $jsonStr = json_encode($param);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $response;
    }
}


/**
 * 发起get请求
 * @param $url
 * @return mixed
 */
function http_get($url){
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    $tmpInfo = curl_exec($curl);     //返回api的json对象
    //关闭URL请求
    curl_close($curl);
    return $tmpInfo;    //返回json对象
}


/**
 * 发起post请求
 * @param $url
 * @param $data
 * @return mixed
 */
function http_post($url,$data){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}


/**
 * 生成雪花算法
 * @return string
 * @throws Exception
 */
function snowflake(){
    $dataCenterId=1;//数据中心
    $workerId=1;//机器ID
    $snowflake=new \Godruoyi\Snowflake\Snowflake($dataCenterId, $workerId);
    //$snowflake->setStartTimeStamp(strtotime('2021-01-29')*1000);
    return $snowflake->id();
}


/**
 * 获取配置
 * @param string $key
 * @return mixed
 */
function dbConfig($key='true'){
    return \think\facade\Db::name('system_setting')->where(['key'=>$key])->value('value');
}


/**
 * 命令行打印
 * @param $info
 * @param int $type
 */
function writeln($info,$type=0){
    $out=new \think\console\Output();
    $out->writeln($info,$type);
}


/**
 * 根据出生年月日获取年龄
 * @param $birth
 * @return false|int|string
 */
function getAgeByBirth($birth)
{
    if(empty($birth)){
        return '18';
    }
    $birth_year = date('Y',strtotime($birth));
    $birth_month = date('m',strtotime($birth));
    $birth_day = date('d',strtotime($birth));
    if (empty($birth_year) || empty($birth_month) || empty($birth_day)) {
        return 18;
    }
    $current_year = date('Y', time());
    $current_month = date('m', time());
    $current_day = date('d', time());
    if ($birth_year >= $current_year) {
        return 18;
    }
    $age = $current_year - $birth_year - 1;
    if ($current_month > $birth_month) {
        return $age + 1;
    } else if ($current_month == $birth_month && $current_day >= $birth_day) {
        return $age + 1;
    } else {
        return $age;
    }
}

/**
 * 写入后台操作日志
 * @param $admin_id
 * @param string $type
 * @param string $executeResult
 */
function writeSystemLog($admin_id,$type='operate',$executeResult=''){
    $data['admin_id']=$admin_id;
    $data['type']=$type;
    $data['execute_result']=$executeResult;
    $data['user_agent']=request()->header('user-agent');
    $data['ip']=request()->ip();
    $data['create_at']=currentTime();
    \think\facade\Db::name('system_operate_log')->insert($data);
}


/**
 * 毫秒时间戳
 * @return float
 */
function millisecond() {
    list($mSec, $sec) = explode(' ', microtime());
    $mSecTime = (float)sprintf('%.0f', (floatval($mSec) + floatval($sec)) * 1000);
    return $mSecTime;
}